using MediatR;
using WMS.Domain;
using WMS.ErrorCode;
using WMS.Infrasturcture.Interfaces;
using WMS.WebApiRead.Application.Command;
using WMS.WebApiRead.DTO;

namespace WMS.WebApiRead.Application.Commandhandler
{
    /// <summary>
    /// 盘点信息详情查询命令处理器（多表联查）
    /// 包含盘点主表信息、明细列表、附件列表
    /// </summary>
    public class InventoryDetailQueryCommandHandler : IRequestHandler<InventoryDetailQueryCommand, ApiResult<InventoryDetailResultDTO>>
    {
        private readonly IBaseRepository<InventoryInfo> inventoryRepository;
        private readonly IBaseRepository<Inventory_check_details> detailsRepository;
        private readonly IBaseRepository<Uploadattachment> attachmentRepository;
        private readonly IBaseRepository<HandlerInfo> handlerRepository;
        private readonly IBaseRepository<WarehouseInfo> warehouseRepository;
        private readonly IBaseRepository<WarehouseDept> deptRepository;
        private readonly IBaseRepository<InventoryTypeInfo> inventoryTypeRepository;

        /// <summary>
        /// 构造函数，注入所有需要的仓储
        /// </summary>
        public InventoryDetailQueryCommandHandler(
            IBaseRepository<InventoryInfo> inventoryRepository,
            IBaseRepository<Inventory_check_details> detailsRepository,
            IBaseRepository<Uploadattachment> attachmentRepository,
            IBaseRepository<HandlerInfo> handlerRepository,
            IBaseRepository<WarehouseInfo> warehouseRepository,
            IBaseRepository<WarehouseDept> deptRepository,
            IBaseRepository<InventoryTypeInfo> inventoryTypeRepository)
        {
            this.inventoryRepository = inventoryRepository;
            this.detailsRepository = detailsRepository;
            this.attachmentRepository = attachmentRepository;
            this.handlerRepository = handlerRepository;
            this.warehouseRepository = warehouseRepository;
            this.deptRepository = deptRepository;
            this.inventoryTypeRepository = inventoryTypeRepository;
        }

        /// <summary>
        /// 处理盘点信息详情查询命令
        /// </summary>
        public async Task<ApiResult<InventoryDetailResultDTO>> Handle(InventoryDetailQueryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // ==================== 多表联查主表信息 ====================
                var inventoryQuery = from inventory in inventoryRepository.GetAll()
                                    where !inventory.IsDeleted && inventory.InventoryCode == request.InventoryCode
                                    join warehouse in warehouseRepository.GetAll()
                                    on inventory.WarehouseId equals warehouse.WarehouseID into warehouseGroup
                                    from warehouse in warehouseGroup.DefaultIfEmpty()
                                    join handler in handlerRepository.GetAll()
                                    on inventory.HandlerrId equals handler.HandlerrId into handlerGroup
                                    from professional in handlerGroup.DefaultIfEmpty()
                                    join dept in deptRepository.GetAll()
                                    on (warehouse != null ? warehouse.WarehouseDeptId : (professional != null ? professional.WarehouseDeptId : 0)) equals dept.WarehouseDeptId into deptGroup
                                    from dept in deptGroup.DefaultIfEmpty()
                                    join inventoryType in inventoryTypeRepository.GetAll()
                                    on inventory.InventoryTypeId equals inventoryType.InventoryTypeId into inventoryTypeGroup
                                    from inventoryType in inventoryTypeGroup.DefaultIfEmpty()
                                    select new
                                    {
                                        Inventory = inventory,
                                        WarehouseName = warehouse != null ? warehouse.WarehouseName : "未分配",
                                        HandlerName = professional != null ? professional.HandlerName : "未分配",
                                        WarehouseDeptId = dept != null ? dept.WarehouseDeptId : (int?)null,
                                        WarehouseDeptName = dept != null ? dept.WarehouseDeptName : "未分配",
                                        InventoryTypeId = inventoryType != null ? inventoryType.InventoryTypeId : 0,
                                        InventoryTypeName = inventoryType != null ? inventoryType.InventoryTypeName : "未分配"
                                    };

                var inventoryInfo = inventoryQuery.FirstOrDefault();

                if (inventoryInfo == null)
                {
                    return new ApiResult<InventoryDetailResultDTO>
                    {
                        Code = ApiResultEnum.查询失败,
                        Message = "盘点信息不存在",
                        Data = null
                    };
                }

                string inventoryCode = inventoryInfo.Inventory.InventoryCode;

                // ==================== 查询盘点明细列表 ====================
                var detailsList = detailsRepository.GetAll()
                    .Where(x => x.InventoryCode == inventoryCode)
                    .Select(x => new InventoryDetailItemDTO
                    {
                        Inventory_check_detailsId = x.Inventory_check_detailsId,
                        InventoryCode = x.InventoryCode,
                        DetailsProductName = x.DetailsProductName,
                        DetailsProductCode = x.DetailsProductCode,
                        SpecificationModel = x.SpecificationModel,
                        DetailsUnit = x.DetailsUnit,
                        BookStock = x.book_stock,
                        BookAmount = x.book_amount,
                        CountedStock = x.counted_stock,
                        CountedStockLocation = x.counted_stock_location,
                        CountedStockRaw = x.counted_stock_raw,
                        CountedStockNumeric = x.counted_stock_numeric,
                        ProfitLossQty = x.profit_loss_qty,
                        ProfitLossAmount = x.profit_loss_amount,
                        Status = x.status,
                        ReferencePrice = x.reference_price,
                        Remark = x.remark
                    })
                    .ToList();

                // ==================== 查询附件列表 ====================
                var attachmentList = attachmentRepository.GetAll()
                    .Where(x => x.InventoryCode == inventoryCode && !x.IsDeleted)
                    .Select(x => new InventoryAttachmentDTO
                    {
                        UploadId = x.UploadId,
                        InventoryCode = x.InventoryCode,
                        UploadUrl = x.UploadUrl,
                        CreateTime = x.CreateTime,
                        CreateName = x.CreateName
                    })
                    .OrderByDescending(x => x.CreateTime)
                    .ToList();

                // ==================== 构建详情结果 ====================
                var result = new InventoryDetailResultDTO
                {
                    InventoryId = inventoryInfo.Inventory.InventoryId,
                    InventoryCode = inventoryInfo.Inventory.InventoryCode,
                    InventoryTypeId = inventoryInfo.Inventory.InventoryTypeId,
                    InventoryTypeName = inventoryInfo.InventoryTypeName,
                    WarehouseId = inventoryInfo.Inventory.WarehouseId,
                    WarehouseName = inventoryInfo.WarehouseName,
                    HandlerrId = inventoryInfo.Inventory.HandlerrId,
                    HandlerName = inventoryInfo.HandlerName,
                    WarehouseDeptId = inventoryInfo.WarehouseDeptId,
                    WarehouseDeptName = inventoryInfo.WarehouseDeptName,
                    InventoryDateTime = inventoryInfo.Inventory.InventoryDateTime,
                    InventoryEndTime = inventoryInfo.Inventory.InventoryEndTime,
                    InventoryContent = inventoryInfo.Inventory.InventoryContent,
                    InventoryQuantity = inventoryInfo.Inventory.InventoryQuantity,
                    SurplusQuantity = inventoryInfo.Inventory.SurplusQuantity,
                    InventoryShortageQuantity = inventoryInfo.Inventory.InventoryShortageQuantity,
                    SurplusAmount = inventoryInfo.Inventory.SurplusAmount,
                    InventoryLossAmount = inventoryInfo.Inventory.InventoryLossAmount,
                    DataStatus = inventoryInfo.Inventory.DataStatus,
                    CreateName = inventoryInfo.Inventory.CreateName,
                    CreateTime = inventoryInfo.Inventory.CreateTime,
                    UpdateName = inventoryInfo.Inventory.UpdateName,
                    UpdateTime = inventoryInfo.Inventory.UpdateTime,
                    DetailsList = detailsList,
                    AttachmentList = attachmentList,
                    IsDeleted = inventoryInfo.Inventory.IsDeleted
                };

                return new ApiResult<InventoryDetailResultDTO>
                {
                    Code = ApiResultEnum.查询成功,
                    Message = "查询盘点详情成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<InventoryDetailResultDTO>
                {
                    Code = ApiResultEnum.查询失败,
                    Message = $"查询盘点详情异常：{ex.Message}",
                    Data = null
                };
            }
        }
    }
}

